package library.and.xps.com.step.view.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jude.utils.JUtils;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoFrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.CreateActiveParams;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseFragment;

public class ActiveInfoSetupFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener, View.OnClickListener {
    private InvokeParam invokeParam;
    private File file = null;//已选择的文件
    private TakePhoto takePhoto;
    Uri imageUri;
    EditText et_activeName, et_activeDesc;
    ImageView iv_img;
    AutoFrameLayout frame_img;
    private String UPLOAD_ACTIVE_SIGN = "UPLOAD_ACTIVE_SIGN";
    CreateActiveParams createActiveParams;

    @Override
    protected int getRes() {
        return R.layout.fragment_setup_active_info;
    }

    @Override
    protected void init(View view) {
        iv_img = (ImageView) view.findViewById(R.id.iv_img);
        frame_img = (AutoFrameLayout) view.findViewById(R.id.frame_img);
        frame_img.setOnClickListener(this);
        et_activeName = (EditText) view.findViewById(R.id.et_active_name);
        et_activeName.setOnClickListener(this);
        et_activeDesc = (EditText) view.findViewById(R.id.et_active_desc);
        et_activeDesc.setOnClickListener(this);
        createActiveParams = new CreateActiveParams();
    }

    @Override
    protected void setData(View view) {

    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void takeSuccess(TResult result) {
        TImage t = result.getImage();
        file = new File(t.getOriginalPath());
        upload(file);
    }

    void upload(final File file) {
        final File[] files = {file};
        final String[] filenames = {"file_upload"};
        try {
            OkHttpClientUtils.postUploadFilesAsync(getActivity(), URLConstants.FILE.FileUpload, files, filenames, new RequestCallback() {
                @Override
                public void onFailure(Request request, Exception e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(ResponceWrapper response) {
                    if (response.getResponcecode() == 200) {
                        Glide.with(getActivity()).load(file)
                                .placeholder(R.mipmap.loading)
                                .bitmapTransform(new RoundedCornersTransformation(getActivity(), 20, 0, RoundedCornersTransformation.CornerType.ALL))
                                .into(iv_img);

                        createActiveParams.setMark(response.getBody());
                        frame_img.setBackground(null);
                    }
                }

                @Override
                public void onStart() {

                }
            }, UPLOAD_ACTIVE_SIGN);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        JUtils.Toast(msg);
    }

    public boolean next() {
        if (getUser() == null||getUser().getTeams().get(0)==null) {
            Snackbar.make(et_activeDesc, "发生错误", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (file == null) {
            Snackbar.make(et_activeDesc, "请添加活动封面", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (TextUtils.isEmpty(et_activeName.getText().toString())) {
            Snackbar.make(et_activeDesc, "请输入活动名称", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (TextUtils.isEmpty(et_activeDesc.getText().toString())) {
            Snackbar.make(et_activeDesc, "请输入活动描述", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        }

        createActiveParams.setTeamid(getUser().getTeams().get(0).getTId());
        createActiveParams.setTaname(et_activeName.getText().toString());
        createActiveParams.setDescribe(et_activeDesc.getText().toString());
        EventBus.getDefault().post(createActiveParams);

        return true;
    }

    @Override
    public void takeCancel() {
        JUtils.Log("选择取消");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_active_name:

                break;
            case R.id.et_active_desc:

                break;
            case R.id.frame_img:
                startTakeImg();
                break;
        }
    }

    void startTakeImg() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);

        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(102400)
                .create();
        takePhoto.onEnableCompress(config, false);
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(800).setAspectY(800);
        builder.setOutputX(800).setOutputY(800);
        builder.setWithOwnCrop(true);
        takePhoto.onPickFromGalleryWithCrop(imageUri, builder.create());
    }
}
